<!--
 * @Description: zzb
 * @Version: 0.0.1
 * @Autor: zzb
 * @Date: 2022-11-22 16:48:42
 * @LastEditors: zzb
 * @LastEditTime: 2023-02-24 11:03:35
-->
<template>
  <div class="app-container">
    <!--用户数据-->
    <div class="content-wrap my-search">
      <el-form
        :model="queryParams"
        size="mini"
        ref="queryForm"
        :inline="true"
        v-show="showSearch"
        label-width="68px"
      >
        <el-form-item label="用户名" prop="loginId">
          <el-input
            v-model="queryParams.loginId"
            placeholder="请输入用户名称"
            clearable
            size="small"
            style="width: 200px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="用户姓名" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入用户名称"
            clearable
            size="small"
            style="width: 200px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <!-- <el-form-item label="手机号码" prop="mobileNo">
            <el-input v-model="queryParams.mobileNo" placeholder="请输入手机号码" clearable size="small" style="width: 240px" @keyup.enter.native="handleQuery" />
          </el-form-item> -->
        <!-- <el-form-item label="状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="用户状态" clearable size="small" style="width: 240px">
              <el-option v-for="dict in statusOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
            </el-select>
          </el-form-item> -->
        <el-form-item label="角色" prop="roles">
          <el-select
            v-model="queryParams.roles"
            filterable
            placeholder="用户角色-可搜索"
            clearable
            size="small"
            style="width: 200px"
          >
            <!-- <el-option label="未拥有任何角色" value="-1" /> -->
            <el-option
              v-for="item in roleOptions"
              :label="item.roleName"
              :key="item.roleId"
              :value="item.roleId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="用户组" prop="groups">
          <el-select
            v-model="queryParams.groups"
            filterable
            placeholder="用户组-可搜索"
            clearable
            size="small"
            style="width: 200px"
          >
            <el-option label="未在任何用户组" :value="-1" />
            <el-option
              v-for="item in groupOption"
              :key="item.groupId"
              :label="item.groupName"
              :value="item.groupId"
            />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="创建时间">
            <el-date-picker v-model="dateRange" size="small" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
          </el-form-item> -->
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <el-row :gutter="10" class="mb8 grid-content">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:user:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:user:edit']"
          v-if="false"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:user:remove']"
          >删除</el-button
        >
      </el-col>

      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getUserList"
      ></right-toolbar>
    </el-row>

    <el-table
      :data="userList"
      v-loading="loading"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column
        label="用户名"
        align="center"
        key="loginId"
        prop="loginId"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="用户姓名"
        align="center"
        key="name"
        prop="name"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="性别"
        align="center"
        key="sex"
        prop="sex"
        :formatter="sexFormat"
        :show-overflow-tooltip="true"
        width="80"
      />
      <el-table-column
        label="电话号码"
        align="center"
        key="mobileNo"
        prop="mobileNo"
        width="120"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          <span>{{
            scope.row.telNo
              ? scope.row.telNo.length > 7
                ? scope.row.telNo
                : "-"
              : "-"
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="手机号码"
        align="center"
        prop="telNo"
        width="120"
      />

      <el-table-column
        label="邮箱"
        align="center"
        key="email"
        prop="email"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          <span>{{
            scope.row.email
              ? scope.row.email.indexOf("@") > -1
                ? scope.row.email
                : "-"
              : "-"
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="所属网站"
        align="center"
        key="siteId"
        prop="siteId"
        width="120"
        :formatter="siteIdFormat"
        show-overflow-tooltip
        v-if="false"
      />
      <el-table-column label="权限" align="center" width="100">
        <template slot-scope="scope">
          <el-popover
            placement="right"
            width="500"
            trigger="manual"
            :ref="`popover-${scope.$index}`"
          >
            <div style="min-height: 65px">
              <p>站点</p>
              <div class="aaaaa" style="min-height: 30px">
                <el-tag type="primary">
                  {{ siteIdFormat(scope.row) }}
                </el-tag>
              </div>
            </div>
            <div style="min-height: 65px">
              <p>角色</p>
              <div class="aaaaa" style="min-height: 30px">
                <dict-tag
                  :options="roleOptions"
                  :value="authForm.roles"
                  :prop="{ value: 'roleId', label: 'roleName' }"
                  v-show="form.userId"
                />
              </div>
            </div>
            <div style="min-height: 65px">
              <p>用户组</p>
              <div class="aaaaa" style="min-height: 30px">
                <el-tag type="primary" v-if="authForm.groups.includes(-1)">
                  未在任何用户组
                </el-tag>
                <dict-tag
                  :options="groupOption"
                  :value="authForm.groups"
                  :prop="{ value: 'groupId', label: 'groupName' }"
                  v-else-if="form.userId"
                />
              </div>
            </div>
            <div style="text-align: right; margin: 0">
              <el-button
                type="primary"
                size="mini"
                @click="scope._self.$refs[`popover-${scope.$index}`].doClose()"
                >确定</el-button
              >
            </div>
            <el-button
              slot="reference"
              size="mini"
              type="text"
              icon="el-icon-search"
              @click="handleUpdate(scope, false)"
              >查看</el-button
            >
          </el-popover>
          <!-- <el-dropdown :hide-on-click="false">
                <span class="el-dropdown-link">
                  点击查看<i class="el-icon-arrow-down el-icon--right" @click="handlePreview(scope.row)"></i>
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item>黄金糕</el-dropdown-item>
                  <el-dropdown-item>狮子头</el-dropdown-item>
                  <el-dropdown-item>螺蛳粉</el-dropdown-item>
                  <el-dropdown-item disabled>双皮奶</el-dropdown-item>
                  <el-dropdown-item divided>蚵仔煎</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown> -->
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" key="available" width="100">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.available"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column
        label="双因子认证"
        align="center"
        key="twoFactorAuthenticationStatus"
        width="100"
      >
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.twoFactorAuthenticationStatus"
            :active-value="1"
            :inactive-value="0"
            @change="handleTwoFactorAuthenticationStatusChange(scope.row)"
            :disabled="scope.row.twoFactorAuthenticationStatus == 0"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="200"
        class-name="small-padding fixed-width"
      >
        <!-- <template slot-scope="scope" v-if="scope.row.userId !== 1"> -->
        <template slot-scope="scope" v-if="scope.row.loginId !== 'dsnwwz'">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope)"
            v-hasPermi="['system:user:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:user:remove']"
            >删除</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-key"
            @click="handleResetPwd(scope.row)"
            v-hasPermi="['system:user:remove']"
            >重置密码</el-button
          >

          <el-dropdown
            size="mini"
            @command="(command) => handleCommand(command, scope.row)"
            v-if="false"
          >
            <span class="el-dropdown-link">
              <i class="el-icon-d-arrow-right el-icon--right"></i>更多
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="handleResetPwd" icon="el-icon-key"
                >重置密码</el-dropdown-item
              >
              <!-- <el-dropdown-item command="handleAuthRole" icon="el-icon-circle-check" v-hasPermi="['system:user:edit']">分配角色</el-dropdown-item> -->
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getUserList"
    />

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog
      v-dialogDrag
      :title="title"
      :visible.sync="open"
      width="800px"
      append-to-body
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户名" prop="loginId">
              <el-popover
                ref="popover"
                placement="right"
                title=""
                width="300"
                trigger="focus"
              >
                <span>
                  请输入用户名-作为登录名使用，不可修改<br />
                  可使用的字符为（A-Z a-z 0-9 _ - .)<br />以字母开头，<br />长度不小于2个字符，<br />不超过15个字符，<br />不能使用空格
                  。
                </span>
                <el-input
                  slot="reference"
                  v-model="form.loginId"
                  placeholder="请输入用户名-作为登录名使用，不可修改"
                  :disabled="!!form.userId"
                  maxlength="15"
                  show-word-limit
                  autocomplete="off"
                />
              </el-popover>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户姓名" prop="name">
              <el-popover
                ref="popover"
                placement="right"
                width="300"
                trigger="focus"
              >
                <span>
                  用户名称可以为汉字或英文字符或数字，<br />长度不小于2个字符，<br />不超过50个字符！
                </span>
                <el-input
                  slot="reference"
                  v-model="form.name"
                  placeholder="请输入用户真实姓名"
                  autocomplete="off"
                  clearable
                  maxlength="50"
                  show-word-limit
                />
              </el-popover>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="!form.userId">
          <el-col :span="12">
            <el-form-item label="密码" prop="password">
              <!-- <div class="showPwd" style="width: 100%;height: 36px;border: 1px solid #009a94;position: absolute;z-index: 9;border-radius: 4px;line-height: 36px;">
                  <i slot="suffix" class="el-icon-view" @click="hiddenPassword(form.password)" style="line-height: 36px;float:right"></i>
                </div> -->
              <el-popover
                ref="popover"
                placement="right"
                width="300"
                trigger="focus"
              >
                <span>
                  必须包含大写字母、小写字母、数字、符号3种<br />长度不小于6个字符，不超过15个字符，注意不要使用空格。
                </span>
                <!-- <el-input
                  class="pwd-ipt"
                  slot="reference"
                  v-model.trim="form.password"
                  placeholder="请输入密码"
                  maxlength="15"
                  show-password
                  type="password"
                  @input="(val) => (form.password = val.replace(' ', ''))"
                  auto-complete="new-password"
                /> -->

                <el-input
                  type="password"
                  class="pwd-ipt"
                  slot="reference"
                  v-model.trim="form.password"
                  placeholder="请输入密码"
                  maxlength="15"
                  @input="
                    (val) => {
                      form.password = val.replace(' ', '');
                      password2 = val.replace(' ', '');
                    }
                  "
                  auto-complete="off"
                  v-show="isShow"
                >
                  <i
                    slot="suffix"
                    class="el-icon-view"
                    @click="hiddenPassword(1, form.password)"
                  ></i>
                </el-input>
                <el-input
                  type="text"
                  slot="reference"
                  v-model.trim="password2"
                  placeholder="请输入密码"
                  maxlength="15"
                  auto-complete="off"
                  v-show="!isShow"
                  @input="
                    (val) => {
                      form.password = val.replace(' ', '');
                      password2 = val.replace(' ', '');
                    }
                  "
                >
                  <i
                    slot="suffix"
                    class="el-icon-view"
                    @click="hiddenPassword(1, form.password)"
                  ></i>
                </el-input>
              </el-popover>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="确认密码" prop="checkpassword">
              <!-- <el-input
                class="pwd-ipt"
                v-model.trim="form.checkpassword"
                placeholder="请输入密码"
                maxlength="15"
                show-password
                type="password"
                @input="(val) => (form.checkpassword = val.replace(' ', ''))"
                auto-complete="new-password"
              /> -->
              <el-input
                type="password"
                class="pwd-ipt"
                v-model.trim="form.checkpassword"
                placeholder="请输入密码"
                maxlength="15"
                @input="
                  (val) => {
                    form.checkpassword = val.replace(' ', '');
                    password3 = val.replace(' ', '');
                  }
                "
                auto-complete="new-password"
                v-show="isShow2"
              >
                <i
                  slot="suffix"
                  class="el-icon-view"
                  @click="hiddenPassword(2, form.checkpassword)"
                ></i>
              </el-input>
              <el-input
                type="text"
                v-model.trim="password3"
                placeholder="请输入密码"
                maxlength="15"
                auto-complete="off"
                v-show="!isShow2"
                @input="
                  (val) => {
                    form.checkpassword = val.replace(' ', '');
                    password3 = val.replace(' ', '');
                  }
                "
              >
                <i
                  slot="suffix"
                  class="el-icon-view"
                  @click="hiddenPassword(2, form.checkpassword)"
                ></i>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="电话" prop="mobileNo">
              <el-input
                v-model="form.mobileNo"
                placeholder="请输入电话"
                maxlength="11"
                show-word-limit
                clearable
                @input="
                  (val) => {
                    form.mobileNo = val.replace(/\D/g, '');
                  }
                "
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="telNo">
              <el-input
                v-model="form.telNo"
                placeholder="请输入手机号"
                maxlength="11"
                show-word-limit
                clearable
                :rules="[
                  {
                    type: 'tel',
                    message: '请输入正确的手机号',
                    trigger: ['blur', 'change'],
                  },
                ]"
                @input="
                  (val) => {
                    form.telNo = val.replace(/\D/g, '');
                  }
                "
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item
              prop="email"
              label="邮箱"
              :rules="[
                {
                  type: 'email',
                  message: '请输入正确的邮箱地址',
                  trigger: ['blur', 'change'],
                },
              ]"
            >
              <el-input v-model="form.email"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="sex">
              <el-select
                v-model="form.sex"
                placeholder="请选择性别"
                style="width: 100%"
              >
                <el-option
                  v-for="dict in sexOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="ip地址" prop="ipAddress">
              <el-input
                v-model="form.ipAddress"
                placeholder="请输入ip绑定地址,不绑定IP请置空！"
                maxlength="30"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属网站" prop="sex">
              <el-select
                v-model="form.siteId"
                placeholder="请选择"
                @change="siteChange"
                style="width: 100%"
              >
                <el-option
                  v-for="dict in siteListOptions"
                  :key="dict.siteId"
                  :label="dict.name"
                  :value="dict.siteId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户角色" prop="roles">
              <el-select
                v-model="form.roles"
                filterable
                multiple
                collapse-tags
                placeholder="请选择用户组"
                @change="userRolesChange"
                style="width: 100%"
              >
                <!-- <el-option label="未拥有任何角色" :value="-1" /> -->
                <el-option
                  v-for="item in roleOptions"
                  :label="item.roleName"
                  :key="item.roleId"
                  :value="item.roleId"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户组" prop="groups">
              <el-select
                v-model="form.groups"
                filterable
                multiple
                collapse-tags
                placeholder="请选择用户组"
                @change="userGroupsChange"
                style="width: 100%"
              >
                <el-option label="未在任何用户组" :value="-1" />
                <el-option
                  v-for="item in groupOption"
                  :key="item.groupId"
                  :label="item.groupName"
                  :value="item.groupId"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item label="部门" prop="depId">
            <!-- <el-select v-model="deptIdCache" placeholder="请选择" @change='getChildProject'>
            <el-option v-for="item in depOptions1" :key="item.depId" :label="item.name" :value="item.depId">
            </el-option>
          </el-select> -->
            <el-col :span="8">
              <el-select
                v-model="form.siteId_dep"
                placeholder="站点"
                @change="siteChangeDep"
              >
                <el-option
                  v-for="dict in siteListOptions2"
                  :key="dict.siteId"
                  :label="dict.name"
                  :value="dict.siteId"
                ></el-option>
              </el-select>
            </el-col>
            <el-col :span="8">
              <el-select
                v-model="form.deptFatherId"
                placeholder="一级部门"
                @change="getChildProject"
              >
                <el-option
                  v-for="(item, k) in depOptions1"
                  :key="k"
                  :label="item.name"
                  :value="item.depId"
                >
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="8">
              <el-select v-model="form.depId" placeholder="请选择">
                <el-option
                  v-for="item in depOptions2"
                  :key="item.depId"
                  :label="item.name"
                  :value="item.depId"
                >
                </el-option>
              </el-select>
            </el-col>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="市县" prop="city" v-if="false">
            <el-select v-model="form.city" clearable placeholder="请选择">
              <el-option
                v-for="(item, key) in cityOption"
                :key="key"
                :label="item"
                :value="item"
              >
              </el-option>
            </el-select>
            <el-select v-model="form.county" clearable placeholder="请选择">
              <el-option
                v-for="(item, key) in countyOption"
                :key="key"
                :label="item"
                :value="item"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row v-if="form.userId">
          <el-col :span="12">
            <el-form-item label="登录时间" prop="timgRange">
              <el-time-picker
                is-range
                v-model="timgRange"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                placeholder="选择时间范围"
                @change="userTimeLimit"
                value-format="HH:mm:ss"
              >
              </el-time-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { on, off } from "element-ui/src/utils/dom";

import {
  listDepAll,
  listDep,
  subList,
} from "@/api/extendApplication/complaints.js";
import { getParentDep } from "@/api/content/article";
import {
  listUser,
  getUser,
  delUser,
  addUser,
  updateUser,
  resetUserPwd,
  updateUserStatus,
  checkLoginIdUnique,
  cancleUserTwoFactorAuthentication,
  settingUserLimit,
  cancelUserLimit,
  getUserPower,
} from "@/api/system/user";
import { listSite } from "@/api/content/net";
import { GroupList } from "@/api/system/userGroup";
import { roleOptionSelect } from "@/api/system/role";
import city from "../city";
import { mapState } from "vuex";
import auth from "@/plugins/auth";
export default {
  data() {
    var validateLoginId = (rule, value, callback) => {
      if (value && !/^[a-zA-Z][a-zA-Z\d_.-]{1,14}$/.test(value)) {
        callback(new Error("用户名格式有误"));
      } else if (!value) {
        callback(new Error("请输入用户名"));
      } else if (!this.form.userId) {
        checkLoginIdUnique({ loginId: value }).then((res) => {
          if (res.code == 200) {
            callback();
          } else {
            callback(new Error(res.msg));
          }
        });
      } else {
        callback();
      }
    };

    var validateName = (rule, value, callback) => {
      if (value && !/^(?:[\u4e00-\u9fa5·a-zA-Z0-9]{2,50})$/.test(value)) {
        callback(new Error("姓名格式有误"));
      } else if (!value) {
        callback(new Error("请输入姓名"));
      } else {
        callback();
      }
    };
    const validatePassword = (rule, value, callback) => {
      let mode = 0;
      if (!value) {
        callback(new Error("密码不能为空"));
      } else if (value.length < 6 || value.length > 15) {
        callback(new Error("长度为6-15个字符"));
      } else if (/\s/.test(value)) {
        callback(new Error("密码不能包含空格"));
      } else {
        if (/\d/.test(value)) mode++; //数字
        if (/[A-Z]/.test(value)) mode++; //大写字母
        if (/[a-z]/.test(value)) mode++; //小写字母
        if (/[\W_]/.test(value)) mode++; //特殊字符

        if (mode < 3) {
          callback(new Error("必须包含大写字母、小写字母、数字、符号3种"));
        }
        callback();
      }
    };

    const validatecheckPassword = (rule, value, callback) => {
      if (!value) {
        callback(new Error("确认密码不能为空"));
      } else if (value != this.form.password) {
        callback(new Error("两次输入的密码必须一致!"));
      } else {
        callback();
      }
    };

    const validateIp = (rule, value, callback) => {
      let regIp =
        /^((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.){3}(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])(?::(?:[0-9]|[1-9][0-9]{1,3}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5]))?$/;
      if (value && !regIp.test(value)) {
        callback(new Error("IP地址格式有误"));
      } else {
        callback();
      }
    };
    const validateTel = (rule, value, callback) => {
      /^(?:(?:\+|00)86)?1[3-9]\d{9}$/;
      let regIp = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/;
      if (value && !regIp.test(value)) {
        callback(new Error("手机号格式有误"));
      } else {
        callback();
      }
    };
    return {
      isShow: true,
      isShow2: true,
      password2: "",
      password3: "",
      loading: false,
      // 当前打开的popover
      activePopover: "",
      authForm: {
        roles: [],
        groups: [],
      },
      //部门级联选择参数
      depOptions1: [],
      depOptions2: [],
      props: {
        // props定义的值根据接口返回的数据定的
        label: "name",
        value: "depId",
        lazy: true,
        lazyLoad(node, resolve) {
          let nodes = [];
          subList({ parentId: node.value }).then((res) => {
            res.data.map((item) => {
              let obj = {
                name: item.name,
                depId: item.depId,
                leaf: node.level >= 1,
              };
              nodes.push(obj);
            });
            resolve(nodes);
          });
        },
        // lazyLoad(node, resolve) {
        //   const { level } = node;
        //   setTimeout(() => {
        //     const nodes = Array.from({ length: level + 1 }).map((item) => ({
        //       value: ++id,
        //       label: `选项${id}`,
        //       leaf: level >= 2,
        //     }));
        //     // 通过调用resolve将子节点数据返回，通知组件数据加载完成
        //     resolve(nodes);
        //   }, 1000);
        // },
      },
      checkList: [],
      // 显示搜索条件
      showSearch: true,
      userList: [],
      total: 0,
      //部门对话框 左侧列表
      siteList: [],
      rightRow: null,
      rightTable: [],
      siteRow: null,
      depRow: null,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      ids: [],
      names: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        mobileNo: undefined,
        status: undefined,
        groups: [-1],
        roles: undefined,
        name: undefined,
        loginId: undefined,
      },
      // 默认密码
      initPassword: undefined,
      // 日期范围
      dateRange: [],
      //用户登录时间
      timgRange: null,
      value1: [new Date(2016, 9, 10, 8, 40), new Date(2016, 9, 10, 9, 40)],
      // 状态数据字典
      statusOptions: [],
      // 性别状态字典
      sexOptions: [],
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      //用户组选项
      groupOption: [],
      //市县
      city: city,

      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {
        groups: [],
        checkpassword:
          process.env.NODE_ENV === "development" ? "Gyx,05896." : "",
        // checkpassword: "",
        password: process.env.NODE_ENV === "development" ? "Gyx,05896." : "",
      },
      // 表单校验
      rules: {
        loginId: [
          {
            required: true,
            validator: validateLoginId,
            trigger: ["blur", "change"],
          },
        ],
        name: [
          {
            required: true,
            validator: validateName,
            trigger: ["blur", "change"],
          },
        ],
        password: [
          {
            required: true,
            validator: validatePassword,
            trigger: ["blur", "change"],
          },
        ],
        checkpassword: [
          {
            required: true,
            validator: validatecheckPassword,
            trigger: ["blur", "change"],
          },
        ],
        ipAddress: [
          {
            required: false,
            validator: validateIp,
            trigger: ["blur", "change"],
          },
        ],
        telNo: [
          {
            required: false,
            validator: validateTel,
            trigger: ["blur", "change"],
          },
        ],
        roles: [
          {
            required: true,
            message: "请选择角色",
            trigger: ["blur", "change"],
          },
        ],
      },

      deptIdCache: null,
      //权限查看   应该没什么用  不想写
      userPower: {},

      //点击修改时，获取用户siteid
      oneUserSiteId: undefined,
      //站点选项
      siteListOptions: [],
      siteListOptions2: [],
    };
  },

  components: {},

  computed: {
    cityOption() {
      let arr = Object.keys(this.city.city);
      return arr;
    },
    countyOption() {
      let arr = this.city.city[this.form.city];
      return arr;
    },
    // ...mapState(["column"],),
    ...mapState({
      roles: (state) => state.user.roles,
      column: (state) => state.column,
    }),
  },

  mounted() {
    // this.getUserList();    //watch 里面获取
    this.getRoleList(); //获取角色
    this.getSiteList(); //获取站点

    this.getDicts("sys_normal_disable").then((response) => {
      this.statusOptions = response.data;
    });
    this.getDicts("sys_user_sex").then((response) => {
      this.sexOptions = response.data;
    });
    this.getConfigKey("sys.user.initPassword").then((response) => {
      this.initPassword = response.msg;
    });
  },
  watch: {
    "column.siteRow.siteId": {
      handler(siteId) {
        siteId = siteId == 0 ? 1 : siteId;
        this.getUserList(); //获取当前站点下的用户列表

        this.getGroupList(siteId); //获取当前站点下的用户组
        this.getDepList(siteId); //获取当前站点下的部门
      },
      deep: true,
      immediate: true,
    },
  },
  methods: {
    hiddenPassword(id, password) {
      console.log(password);
      if (id == 1) {
        if (password.length > 0) {
          this.isShow = !this.isShow;
          // if (!this.isShow) {
          //   //this.password2 = password.replace(/./g, () => "*");
          //   this.password2 = password;
          //   console.log(666, this.password2);
          // }
        }
      } else {
        if (password.length > 0) {
          this.isShow2 = !this.isShow2;
          // if (!this.isShow2) {
          //   // this.password3 = password.replace(/./g, () => "*");
          //   this.password3 = password;
          //   console.log(666, this.password3);
          // }
        }
      }
    },
    //用户列表
    getUserList() {
      console.log("this.column:用户列表", this.column);
      this.queryParams.siteId = this.column.siteRow.siteId;
      console.log("this.queryParams.siteId: ", this.queryParams.siteId);
      this.loading = true;
      listUser(this.queryParams).then((response) => {
        this.userList = response.data.list;
        this.total = response.data.totalCount;
        this.loading = false;
      });
    },
    //获取所有站点
    getSiteList() {
      listSite().then((res) => {
        this.siteListOptions2 = res.data;

        if (auth.hasRoleOr(["admin", "wz-admin"])) {
          this.siteListOptions = [
            { siteId: this.CONSTANCE.siteId, name: "平台系统" },
            ...res.data,
          ];
        }
        // res.data.unshift({ siteId: this.CONSTANCE.siteId , name: "平台系统" });
      });
    },
    /** 查询角色列表 */
    getRoleList() {
      roleOptionSelect().then((response) => {
        this.roleOptions = response.data;
      });
    },
    getGroupList(siteId) {
      siteId &&
        GroupList({ siteId }).then((res) => {
          this.groupOption = res.data;
        });

      // let _siteId = siteId || this.column.siteRow.siteId;
      // _siteId &&
      //   GroupList({ siteId: _siteId }).then((res) => {
      //     this.groupOption = res.data;
      //   });
    },
    //获取当前站点 或 选中站点的 投稿部门
    getDepList(siteId) {
      listDep({ siteId }).then((res) => {
        this.depOptions1 = res.data;
      });
      // let _siteId = siteId || this.column.siteRow.siteId;
      // _siteId &&
      //   listDep({ siteId: _siteId }).then((res) => {
      //     this.depOptions1 = res.data;
      //   });
    },
    //获取全部站点 或 选中站点的 投稿部门
    getAllDepList(siteId) {
      listDepAll({ siteId }).then((res) => {
        res.data.forEach((item) => {
          this.depOptions1.push(...item.departmentList);
        });
      });
      // let _siteId = siteId || this.column.siteRow.siteId;
      // _siteId &&
      //   listDep({ siteId: _siteId }).then((res) => {
      //     this.depOptions1 = res.data;
      //   });
    },
    //点击部门
    haldleClickColumn(depId) {
      subList({ parentId: this.depRow.depId || depId }).then((res) => {
        // this.$refs.xTree.loadData(res.data);
        this.rightTable = res.data;
      });
    },

    // 用户状态修改
    handleStatusChange(row) {
      let text = row.available == "1" ? "启用" : "停用";
      this.$confirm("确认要" + text + '"' + row.name + '"用户吗?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return updateUserStatus({
            userId: row.userId,
            available: row.available,
          });
        })
        .then(() => {
          this.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.available = row.available === 0 ? 1 : 0;
        });
    },
    // 双因子认证  管理员关闭  	switch 状态发生变化时的回调函数	新状态的值
    handleTwoFactorAuthenticationStatusChange(row) {
      if (row.twoFactorAuthenticationStatus == 1) return;
      this.$confirm(
        `此操作将关闭用户${row.name}的双因子认证登录, 是否继续?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          cancleUserTwoFactorAuthentication({ userId: row.userId }).then(
            (res) => {
              this.$message({
                type: "success",
                message: "操作成功!",
              });
            }
          );
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消操作",
          });
          row.twoFactorAuthenticationStatus = 1;
        });
    },
    /**
     * 设置用户登录时间，。change时改变
     */
    userTimeLimit(time) {
      if (!time) {
        cancelUserLimit({
          userId: this.form.userId,
        }).then((res) => {
          this.$message({
            type: "success",
            message: "登录时间已清空!",
          });
        });
      } else {
        settingUserLimit(
          this.addDateRange({ userId: this.form.userId }, this.timgRange)
        ).then((res) => {
          this.$message({
            type: "success",
            message: "登录时间已设置!",
          });
        });
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getUserList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.userId);
      this.names = selection.map((item) => `${item.name}(${item.loginId})`);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    // 公告状态字典翻译
    sexFormat(row, column) {
      return this.selectDictLabel(this.sexOptions, row.sex);
    },
    siteIdFormat(row, column) {
      return this.selectDictLabel(
        this.siteListOptions,
        row.siteId,
        "siteId",
        "name"
      );
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加用户";
    },
    /** 修改按钮操作
     * 返回的部门是deptid   用的时候是depid
     *
     */
    async handleUpdate(scope, flag = true) {
      let row = scope.row;
      this.reset();
      const userId = row.userId || this.ids;
      const siteId = row.siteId;
      if (siteId != this.column.siteRow.siteId) {
        await this.siteChange(siteId);
      }
      await getUser(userId).then((res) => {
        // 回显登录时间

        this.timgRange =
          res.data.userLimit.startTime && res.data.userLimit.endTime
            ? [res.data.userLimit.startTime, res.data.userLimit.endTime]
            : [];

        if (res.data.groups.includes(-1)) {
          if (res.data.groups.length == 1) {
            res.data.groups = [-1];
          } else {
            let i = res.data.groups.findIndex((item) => {
              return item == -1;
            });
            res.data.groups.splice(i, 1);
          }
        }
        if (res.data.roles.includes(-1)) {
          if (res.data.roles.length == 1) {
            res.data.roles = [-1];
          } else {
            let i = res.data.roles.findIndex((item) => {
              return item == -1;
            });
            res.data.roles.splice(i, 1);
          }
        }

        this.form = res.data;

        if (flag == false) {
          this.activePopover && scope._self.$refs[this.activePopover].doClose();

          this.authForm = {
            groups: this.form.groups,
            roles: this.form.roles,
          };
          this.$nextTick(() => {
            scope._self.$refs[`popover-${scope.$index}`].doShow();
          });
          this.activePopover = `popover-${scope.$index}`;
          on(document, "click", this.handleDocumentClick);

          return;
        }
        this.$nextTick(() => {
          this.getFatherDepId(res.data.depId);
        });
      });

      getUserPower({ userId: row.userId }).then((res) => {
        console.log("🚀 ~ file: list.vue:813 ~ getUserPower ~ res", res);
      });
    },
    handleDocumentClick() {
      this.activePopover && this.$refs[this.activePopover].doClose();
      off(document, "click", this.handleDocumentClick);
    },

    //查看用户权限
    handlePreview(row) {},
    //获取父部门id
    getFatherDepId(depId) {
      getParentDep({ depId })
        .then((res) => {
          // this.open = true;
          // this.title = "修改用户";
          // return;
          // this.parDepId[length] = res.data.depId;

          if (!res.data.depId) {
            this.form.depId = "";
            this.open = true;
            this.title = "修改用户";
            return;
          }
          let siteId = res.data.siteId;
          this.form.siteId_dep = res.data.siteId;
          siteId ? this.getDepList(siteId) : this.getAllDepList(siteId); //获取当前站点下的部门
          this.deptIdCache = res.data.depId;
          this.form.deptFatherId = res.data.depId;
          this.getChildProject(res.data.depId);
        })
        .then(() => {});
    },
    // 获取子层数据
    getChildProject(parentId) {
      parentId &&
        subList({ parentId }).then((res) => {
          if (res.code == 200) {
            this.depOptions2 = res.data;
            this.open = true;
            this.title = "修改用户";
          } else {
            this.$message.error("获取项目数据失败");
          }
        });
    },
    //对话框  站点变化时。获取对应的部门和用户组列表
    async siteChange(siteId) {
      siteId = siteId == 1 ? 0 : siteId;
      siteId && (await this.getGroupList(siteId)); //获取当前站点下的用户组
      // siteId ? this.getDepList(siteId) : this.getAllDepList(siteId); //获取当前站点下的部门
      //  this.form.roles=[-1]
      this.form.groups = [-1];
      // this.form.depId = "";
      // this.form.deptFatherId = "";
      // this.form.deptIdCache = undefined;
    },
    //对话框  站点变化时。获取对应的部门和用户组列表
    async siteChangeDep(siteId) {
      siteId = siteId == 1 ? 0 : siteId;
      // siteId && (await this.getGroupList(siteId)); //获取当前站点下的用户组
      siteId ? this.getDepList(siteId) : this.getAllDepList(siteId); //获取当前站点下的部门
      //  this.form.roles=[-1]
      // this.form.groups = [-1];
      this.form.depId = "";
      this.form.deptFatherId = "";
      this.form.deptIdCache = undefined;
      this.depOptions2 = [];
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleResetPwd":
          this.handleResetPwd(row);
          break;
        case "handleAuthRole":
          this.handleAuthRole(row);
          break;
        default:
          break;
      }
    },
    /** 重置密码按钮操作 */
    handleResetPwd(row) {
      this.$prompt('请输入"' + row.name + '"的新密码', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        // inputPlaceholder: this.initPassword,
        inputPlaceholder: "请输入新密码",
        // inputPattern: /^.{5,20}$/,
        inputValidator: (value) => {
          let mode = 0;
          if (!value) {
            value = this.initPassword;
          }
          if (!value) {
            return "密码不能为空";
          } else if (value.length < 6 || value.length > 15) {
            return "长度为6-15个字符";
          } else {
            if (/\d/.test(value)) mode++; //数字
            if (/[A-Z]/.test(value)) mode++; //大写字母
            if (/[a-z]/.test(value)) mode++; //小写字母
            if (/[\W_]/.test(value)) mode++; //特殊字符

            if (mode < 3) {
              return "必须包含大写字母、小写字母、数字、符号3种";
            }
          }
        },
        // inputErrorMessage: "用户密码长度必须介于 5 和 20 之间",
      })
        .then(({ value }) => {
          if (!value) {
            value = this.initPassword;
          }
          resetUserPwd({
            loginId: row.loginId,
            password: value,
            available: row.available,
            userId: row.userId,
            name: row.name,
          }).then((response) => {
            this.msgSuccess("修改成功，新密码是：" + value);
          });
        })
        .catch(() => {});
    },
    /** 分配角色操作 */
    handleAuthRole: function (row) {
      const userId = row.userId;
      this.$router.push("/auth/role/" + userId);
    },
    /**新增用户   用户组改变时*/
    userGroupsChange(group) {
      if (group[0] == -1) {
        this.form.groups.shift();
      } else if (group[group.length - 1] == -1) {
        this.form.groups = [-1];
      }
    },
    /**新增用户   角色改变时*/
    userRolesChange(roles) {
      if (roles[0] == -1) {
        this.form.roles.shift();
      } else if (roles[roles.length - 1] == -1) {
        this.form.roles = [-1];
      }
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.userId != undefined) {
            updateUser(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getUserList();
            });
          } else {
            addUser(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getUserList();
            });
          }
        }
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.deptIdCache = null;
      this.form = {
        userId: undefined,
        name: undefined,
        password: process.env.NODE_ENV === "development" ? "Gyx,05896." : "",
        password: "",
        checkpassword:
          process.env.NODE_ENV === "development" ? "Gyx,05896." : "",
        checkpassword: "",

        mobileNo: undefined,
        telNo: undefined,
        email: undefined,
        sex: "0",
        lastModifyPwdTime: undefined,
        loginId: undefined,
        roles: [31],
        groups: [-1],
        depId: "",
        ipAddress: "",
        city: undefined,
        county: undefined,
        siteId: this.column.siteRow.siteId || this.CONSTANCE.siteId,

        available: 1,
      };
      this.resetForm("form");
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.userId || this.ids.join(",");
      const names = row.userId
        ? `${row.name}(${row.loginId})`
        : this.names.join(",");
      this.$confirm('是否确认删除用户 " ' + names + ' " 的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return delUser({ userIds: userIds });
        })
        .then(() => {
          this.getUserList();
          this.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
  },
};
</script>

<style scoped lang="scss">
.app-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}

::v-deep .pwd-ipt {
  .el-input__inner {
    -webkit-text-security: disc !important;
  }
}
::v-deep .complaints .el-dialog__body {
  width: 100%;
  // height: calc(100vh - 100px);
  height: 50vw;
  display: flex;
  flex-direction: row;
  position: relative;
  border: 1px solid #ccc;
  .complaints_l {
    overflow: auto;
    min-width: 240px;
    height: 100%;
  }
  .complaints_r {
    overflow: auto;
    padding: 0 10px;
    // height: 100%;
    border-left: 1px solid #ccc;
    box-sizing: content-box;
    flex: 1;
  }
}
</style>
